package com.apache.seq.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.apache.api.api.ApiService;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.database.constant.Validator;
import com.apache.rpc.common.JsonEntityParese;
import com.apache.rpc.common.XMLMapParse;

import net.sf.json.JSONObject;

/**
 * description: Http或Https访问action
 */
@Controller
@RequestMapping("seq/service/")
public class RestfullSeqAction {

	@Autowired
	private ApiService seqService;

	/**
	 * description:  接口统一调用方法
	 */
	@RequestMapping("doService.action")
	public void doService(HttpServletRequest request, HttpServletResponse response) {
		try {
			String paramStr = request.getParameter("params");
			Map<String, Object> headMap = new HashMap<String, Object>();
			Map<String, Object> bodyMap = new HashMap<String, Object>();
			XMLMapParse.instance().xmlGetData(paramStr, headMap, bodyMap);
			ParamsVo vo = new ParamsVo();
			vo.setMethodKey(headMap.get("MethodCode").toString());
			vo.setParams(bodyMap);
			getResultInfo(vo, request, response);
		} catch (Exception e) {
		}
	}

	/**
	 * description:  系统统一接口(restfull--post)
	 */
	@RequestMapping(value = "/doService/", method = RequestMethod.POST)
	public void doServiceForRf(HttpServletRequest request, HttpServletResponse response) {
		restfulRequest(request, response);
	}

	/**
	 * description:  系统统一接口(restfull--get)
	 */
	@RequestMapping(value = "/doService/", method = RequestMethod.GET)
	public void serviceForRf(HttpServletRequest request, HttpServletResponse response) {
		restfulRequest(request, response);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void restfulRequest(HttpServletRequest request, HttpServletResponse response) {
		ParamsVo vo = new ParamsVo();
		String reqMsg = null;
		try {
			reqMsg = IOUtils.toString(request.getInputStream(), "UTF-8");//以流的方式传参
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (Validator.isNull(reqMsg)) {//xml参数
			String paramStr = request.getParameter("params");
			if (Validator.isNotNull(paramStr)) {
				Map<String, Object> headMap = new HashMap<String, Object>();
				Map<String, Object> bodyMap = new HashMap<String, Object>();
				XMLMapParse.instance().xmlGetData(paramStr, headMap, bodyMap);
				vo.setMethodKey(headMap.get("MethodCode").toString());
				vo.setParams(bodyMap);
			} else {
				String methodCode = request.getParameter("MethodCode");
				Map<String, Object> bodyMap = getRequestParam(request);
				vo.setMethodKey(methodCode);
				vo.setParams(bodyMap);
			}
		} else {
			Map<String, Object> headMap = new HashMap<String, Object>();
			Map<String, Object> bodyMap = new HashMap<String, Object>();
			XMLMapParse.instance().xmlGetData(reqMsg, headMap, bodyMap);
			vo.setMethodKey(headMap.get("MethodCode").toString());
			vo.setParams(bodyMap);
		}
		getResultInfo(vo, request, response);
	}

	private void getResultInfo(ParamsVo vo, HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		try {
			ResultEntity entity = seqService.doService(vo);
			if (Validator.isEmpty(entity)) {
				entity = new ResultEntity();
				entity.setResult("false");
				entity.setMessage("接口调用失败！");
			}
			String callback = request.getParameter("callback");
			PrintWriter out = response.getWriter();
			if (Validator.isNull(callback)) {
				String paramType = request.getParameter("ParamType");
				if ("json".equalsIgnoreCase(paramType))
					result = JsonEntityParese.instance().beanToJson(entity);
				else
					result = JsonEntityParese.instance().toXml(entity);
				response.setContentType("text/html; charset=UTF-8");
				out.print(result);
			} else {///支持jsonp数据格式
				response.setContentType("application/javascript");
				if (Validator.isEmpty(entity.getEntity())) {
					ResultMsg msg = new ResultMsg("F", "操作失败");
					JSONObject json = JSONObject.fromObject(msg);
					result = json.toString();
				} else {
					JSONObject json = JSONObject.fromObject(entity);
					result = json.toString();
				}
				out.print(callback + "(" + result + ")");
			}
			out.flush();
		} catch (Exception e) {
		}
	}

	private Map<String, Object> getRequestParam(HttpServletRequest request) {
		Map<String, Object> bodyMap = new HashMap<String, Object>();
		Set keSet = request.getParameterMap().entrySet();
		for (Iterator itr = keSet.iterator(); itr.hasNext();) {
			Map.Entry me = (Map.Entry) itr.next();
			String ok = String.valueOf(me.getKey());
			if ("ParamType".equals(ok) || "callback".equals(ok) || "MethodCode".equals(ok))
				continue;
			Object ov = me.getValue();
			String[] value = new String[1];
			if (ov instanceof String[]) {
				value = (String[]) ov;
			} else {
				value[0] = ov.toString();
			}
			if (value.length > 0) {
				bodyMap.put(ok.toString(), value[0]);
				request.setAttribute(ok.toString(), value[0]);
			}
		}
		return bodyMap;
	}

}
